package com.hx.zhg.web.controller.wx;

import com.hx.zhg.service.system.WxSystemService;
import com.hx.zhg.service.wx.WxService;
import com.hx.zhg.service.wx.vo.SendTemplateMsgVo;
import com.hx.zhg.util.HttpClientUtil;
import com.hx.zhg.util.JsonUtils;
import com.hx.zhg.util.StringUtilExt;
import com.hx.zhg.web.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhenghegong on 2020/4/17.
 */
@Api(tags = "微信公众号接口")
@RestController
@RequestMapping("/wx")
public class WxController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(WxController.class);

    @Autowired
    private WxSystemService wxSystemService;

    private WxService wxService;

    @Value("${hx.wx.appid}")
    public String appId;

    @Value("${hx.wx.secret}")
    public String secret;

    @RequestMapping(method = RequestMethod.GET)
    public String get(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        String result = "";
        if (wxSystemService.checkSignature(signature, timestamp, nonce)) {
            result = echostr;
        }
        return result;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String post(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setCharacterEncoding("UTF-8");
        // 调用核心业务类接收消息、处理消息
        return wxService.processRequest(request);
    }

    @ApiOperation(value = "获取AppId", notes = "获取AppId")
    @RequestMapping(value = "/getAppId", method = RequestMethod.GET)
    public String getAppId() {
        return appId;
    }

    @ApiOperation(value = "通过CODE获取openId", notes = "通过CODE获取openId")
    @RequestMapping(value = "/getOpenId", method = RequestMethod.GET)
    public String getOpenId(String code, javax.servlet.http.HttpServletRequest request) {
        String result = "";
        try {
            log.info(String.format("【*】通过CODE获取openId：param->code:【%s】", code));
            if (code != null) {
                String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
                result = HttpClientUtil.doHttpGetRequest(url);
            }
        } catch (Exception e) {
            log.error(String.format("system throw exception error: %s; HEADERS: %s", getHeaders(request), e));
            return this.retInternalErrorDefault();
        }
        return result;
    }

    @ApiOperation(value = "通过Code获取用户信息", notes = "通过Code获取用户信息")
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    public String getUserInfo(String code, HttpServletRequest request) {
        String userResult = "";
        try {
            log.info(String.format("【*】通过Code获取用户信息：param->code:【%s】", code));
            if (code != null) {
                String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
                String openResult = HttpClientUtil.doHttpGetRequest(url);
                Map<String, Object> openResultMap = JsonUtils.jsonToMap(openResult);
                String access_token = String.valueOf(openResultMap.get("access_token"));
                String openId = String.valueOf(openResultMap.get("openid"));
                String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openId + "&lang=zh_CN";
                userResult = HttpClientUtil.doHttpGetRequest(userInfoUrl);
                //解决昵称乱码
                if (StringUtilExt.notBlank(userResult)) {
                    Map<String, Object> stringObjectMap = JsonUtils.jsonToMap(userResult);
                    String nickname = String.valueOf(stringObjectMap.get("nickname"));
                    stringObjectMap.put("nickname", new String(nickname.getBytes("ISO-8859-1"), "UTF-8"));
                    userResult = JsonUtils.objToJson(stringObjectMap);
                }
            }
        } catch (Exception e) {
            log.error(String.format("system throw exception error: %s; HEADERS: %s", getHeaders(request), e));
            return this.retInternalErrorDefault();
        }
        return userResult;
    }

    @ApiOperation(value = "发送模版消息", notes = "发送模版消息")
    @RequestMapping(value = "/sendTemplateMsg", method = RequestMethod.POST,
            consumes = {MediaType.APPLICATION_JSON_VALUE},
            produces = {MediaType.APPLICATION_JSON_VALUE})
    @ResponseBody
    public String sendTemplateMsg(@RequestBody @Valid SendTemplateMsgVo sendTemplateMsgVo, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) {
        Map map = new HashMap();
        try {
            validData(bindingResult, response);


        } catch (Exception e) {
            log.error(String.format("system throw exception error: %s; HEADERS: %s", getHeaders(request), e));
            return this.retInternalErrorDefault();
        }
        return retSuccess(map);
    }
}
